﻿using System;
using System.Collections.Generic;

namespace NewsMine.Logging
{

    /// <summary>
    /// A timer that does not leak memory by using static hashtables.
    /// 
    /// To use: 
    /// 
    /// using(LoggingTimer timer = new LoggingTimer("Time-Sensitive Code")) 
    /// {
    ///         // actions you want to time
    /// }
    /// 
    /// </summary>
    public class LoggingTimer : IDisposable
    {
        readonly long _start;
        readonly String _commandName;
        readonly String _commandParameters;

        volatile bool _stopped;
        INewsMineLogger _logger = NewsMineLogManager.GetLogger("Com.NewsMine.Core.Common.Logging.LoggingTimer");

        public LoggingTimer(String commandName, String commandParameters)
        {
            _start = DateTime.Now.Ticks;

            _commandName = commandName;
            _commandParameters = commandParameters;

            string msg = string.Format("Starting call: {0}", commandName);

            _logger.Info(msg);

        }



        public void Stop()
        {

            long ms = DateTime.Now.Ticks - _start;
            TimeSpan ts = new TimeSpan(ms);

            String timeMsg = string.Format("Ending call {1}: Execution Time={0:0.000} seconds;", ts.TotalSeconds, _commandName);

            Dictionary<object, object> properties = new Dictionary<object, object>();
            properties.Add("ExecutionTime", ts.Milliseconds);
            properties.Add("CodeBlockName", _commandName);
            properties.Add("CodeBlockParams", _commandParameters);

            _logger.Info(timeMsg, properties);

            _stopped = true;

        }

        #region IDisposable Members

        public void Dispose()
        {
            if (!_stopped)
                Stop();
        }

        #endregion
    }
}
